package com.ebt.m.homepage;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.ebt.m.AppContext;
import com.ebt.m.R;
import com.ebt.m.commons.utils.Logger;
import com.ebt.m.commons.widgets.BaseRxFragment;
import com.ebt.m.data.bean.UserInfo;
import com.ebt.m.data.rxModel.apibean.DynamicsCountData;
import com.ebt.m.data.rxModel.apibean.PerformanceAll;
import com.ebt.m.databinding.FragmentDynamicBinding;
import com.ebt.m.event.HomeUpdateSearchLabelEvent;
import com.ebt.m.jpush.DoJPush;
import com.ebt.m.jpush.JPushResult;
import com.ebt.m.jpush.JPushUtil;
import com.ebt.m.msgnote.view.MsgCenterActivity;
import com.ebt.m.presenter.HomePageContract;
import com.ebt.m.presenter.HomePagePresenter;
import com.ebt.m.utils.TalkingDataUtil;
import com.ebt.m.utils.android.EBTUserInfoHelper;
import com.ebt.m.utils.netstatus.NetChangedEvent;
import com.ebt.m.wiki.event.EFilter;
import com.ebt.m.wiki.view.ProductItemView1;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

/**
 * 首页
 *
 * @author Andy.Wang
 */
public class DynamicFragment extends BaseRxFragment implements HomePageContract.IView, JPushUtil.OnJPushReceivedListener {

    ActiveView activeContent;
    PerformanceView performanceContent;
    ProductSearchListView searchListView;
    HomeProposalContainer opportunityContent;
    ImageView messageNew;
    private HomePagePresenter homePagePresenter;
    private UserInfo userLicenceInfo;
    private FragmentDynamicBinding dynamicBinding;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        JPushUtil.registerJPushReceivedListener(this);
        homePagePresenter = new HomePagePresenter(getActivity(), this);
        userLicenceInfo = AppContext.getCurrentUser();
        homePagePresenter.getAuthenticationStatus();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        dynamicBinding = FragmentDynamicBinding.inflate(inflater);
        View view = dynamicBinding.container;
        activeContent = dynamicBinding.activeContent;
        performanceContent = dynamicBinding.performanceContent;
        opportunityContent = dynamicBinding.opportunityContent;
        searchListView = dynamicBinding.searchList;
        messageNew = dynamicBinding.newMessage;

        searchListView.addFlag(ProductItemView1.FLAG_DYNAMIC); // 首页的产品点击 -> 制作计划书
        return view;
    }

    private void updateHeaderView() {
        messageNew.setVisibility(View.GONE);
        int appBarLayoutColor = getResources().getColor(R.color.common_bg_bar);
        int companyNameColor = getResources().getColor(R.color.white);
        int companyNameColorBlack = getResources().getColor(R.color.txt_color_333333);
        dynamicBinding.appLayout.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {
            int appBarLayoutScrollRange = appBarLayout.getTotalScrollRange();
            int activeHeight = dynamicBinding.activeContent.getHeight();
            float fraction = 0f;
            fraction = 1 - (appBarLayoutScrollRange + verticalOffset) * 1.0f / activeHeight;
            if (fraction < 0) fraction = 0;
            if (fraction < 0.8f) {
                dynamicBinding.actionMessage.setImageResource(R.drawable.ic_message_new);
            } else if (fraction > 0.9f) {
                dynamicBinding.actionMessage.setImageResource(R.drawable.ic_message_transparent);
            }
            dynamicBinding.toolbar.setBackgroundColor(getCurrentColor(fraction, Color.WHITE, appBarLayoutColor));
            dynamicBinding.companyName.setTextColor(getCurrentColor(fraction, companyNameColorBlack, companyNameColor));

        });
    }

    public static int getCurrentColor(float fraction, int startColor, int endColor) {
        int redCurrent;
        int blueCurrent;
        int greenCurrent;
        int alphaCurrent;

        int redStart = Color.red(startColor);
        int blueStart = Color.blue(startColor);
        int greenStart = Color.green(startColor);
        int alphaStart = Color.alpha(startColor);

        int redEnd = Color.red(endColor);
        int blueEnd = Color.blue(endColor);
        int greenEnd = Color.green(endColor);
        int alphaEnd = Color.alpha(endColor);

        int redDifference = redEnd - redStart;
        int blueDifference = blueEnd - blueStart;
        int greenDifference = greenEnd - greenStart;
        int alphaDifference = alphaEnd - alphaStart;

        redCurrent = (int) (redStart + fraction * redDifference);
        blueCurrent = (int) (blueStart + fraction * blueDifference);
        greenCurrent = (int) (greenStart + fraction * greenDifference);
        alphaCurrent = (int) (alphaStart + fraction * alphaDifference);

        return Color.argb(alphaCurrent, redCurrent, greenCurrent, blueCurrent);
    }

    @Override
    public void onResume() {
        super.onResume();
        updateDataWithoutCompany();
        dynamicBinding.setUser(userLicenceInfo);
        dynamicBinding.setClick(this);
    }

    private void updateDataWithoutCompany() {
        //更新新契约数据
        homePagePresenter.getPerformanceData();
        //更新本月活动量
        homePagePresenter.getActiveCustomerData();
    }

    private void updateDataWithCompany() {
        if (userLicenceInfo.getCompanyInfo() != null)
            searchListView.update();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        updateHeaderView();
    }

    @Override
    public void showActiveCustomer(DynamicsCountData countData) {
        activeContent.update(countData);
    }

    @Override
    public void updatePerformanceView(PerformanceAll performanceAll) {
        performanceContent.update(performanceAll);
    }

    @Override
    public void updateRegisterCompandy(UserInfo loginUserResult) {
        if (loginUserResult == null) return;
        if (!loginUserResult.isRegisterCompany()) {
            AppContext.loginOut(getActivity());
            return;
        }
        AppContext.getCurrentUser().set(loginUserResult);
        EBTUserInfoHelper.saveUserKEY(AppContext.getCurrentUser());
        dynamicBinding.setUser(AppContext.getCurrentUser());
        updateDataWithCompany();
    }

    @Override
    public void onJPushReceived(JPushResult result) {
        try {
            int pushType = result.pushType;
//            if (pushType == DoJPush.JPush_Type_Message && !TextUtils.isEmpty(result.message.topic)) {
//                String topic = result.message.topic;
//                switch (topic) {
//                    case JPushUtil.TOPIC_BUSINESSOPPORTUNITY:
//                        messageNew.setVisibility(View.VISIBLE);
//                        break;
//                }
//            }
            if (pushType == DoJPush.JPush_Type_Message) {
                messageNew.setVisibility(View.VISIBLE);
            }

        } catch (Exception e) {
            Logger.e(e);
        }
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            updateDataWithoutCompany();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        JPushUtil.unregisterJPushReceivedListener(this);
    }

    @Subscribe
    public void onBrandSelected(EFilter filter) {
        searchListView.update(filter.brand);
        opportunityContent.update(filter.brand);
        dynamicBinding.appLayout.setExpanded(false, true);
    }

    @Subscribe
    public void onSearchLabelUpdate(HomeUpdateSearchLabelEvent labelEvent) {
        getActivity().runOnUiThread(() -> opportunityContent.update(labelEvent.brand));
    }

    @Subscribe
    public void onNetChangedEvent(NetChangedEvent event) {
        if (event.onNetConnected) {
            homePagePresenter.getAuthenticationStatus();
            updateDataWithoutCompany();
        }
    }

    public void gotoMessage(View v) {
        TalkingDataUtil.onEventWithAgentId(TalkingDataUtil.TYPE_MESSAGE_CENTER_v270);
        messageNew.setVisibility(View.GONE);
//        Intent intent = new Intent(getActivity(), MessageCenterActivity.class);
//        startActivity(intent);
        Intent intent = new Intent(getActivity(), MsgCenterActivity.class);
        startActivity(intent);
//        Bundle b = new Bundle();
//        b.putString(JPUSH_DATA_EXTRA, "{\"agentId\":13599,\"companyId\":1800,\"content\":\"测试消息0801\",\"jumpMode\":2,\"title\":\"系统提示\",\"type\":4,\"typeName\":\"系统消息\",\"url\":\"http://www.baidu.com\"}");
//        DoJPush.doJPushReceived(JPush_Type_Click, b);
    }
}
